package com.example.peibei.ui.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dingtao.common.bean.Choose;
import com.dingtao.common.bean.GetComment;
import com.dingtao.common.bean.ListResult;
import com.dingtao.common.bean.PaidanList2;
import com.dingtao.common.bean.PaidanListResult;
import com.dingtao.common.bean.PayOrder;
import com.dingtao.common.bean.PayResult;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.WDFragment;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.OnCallback;
import com.example.peibei.R;
import com.example.peibei.base.SpConstant;
import com.example.peibei.service.presenter.ChooseServicePresenter;
import com.example.peibei.service.presenter.ConsumerOrderListPresenter;
import com.example.peibei.service.presenter.PaidanCancenlPresenter;
import com.example.peibei.ui.activity.ChooseOrderContent2Activity;
import com.example.peibei.ui.activity.PaiDanOrderDetailActivity;
import com.example.peibei.ui.adapter.PaidanLists1Adapter;
import com.example.peibei.ui.weight.SelectRequestPaidan;
import com.example.peibei.wxapi.WXPayEntryActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;
import java.util.Random;

import butterknife.BindView;

public class PaidanList1Fragment extends WDFragment {
    @BindView(R.id.rv_bill)
    RecyclerView rv_bill;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    PaidanLists1Adapter adapter;
    ConsumerOrderListPresenter consumerOrderListPresenter;
    private ChooseServicePresenter presenter1;
    private PaidanCancenlPresenter presenter2;

    SPUtils spUtils;
    String token;
    PaidanList2 item;
    String type;
    int payType;

    public PaidanList1Fragment setType(String type) {
        this.type = type;
        return this;
    }

    @Override
    public String getPageName() {
        return "list1"+ new Random().nextInt();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_paidan_list1;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        spUtils = new SPUtils(getActivity(), SpConstant.USER_TOKEN);
        token = spUtils.getString(SpConstant.USER_TOKEN);

        presenter1 = new ChooseServicePresenter(new ChooseServiceCall());
        presenter2 = new PaidanCancenlPresenter(new CancelCall());
        adapter = new PaidanLists1Adapter();
        adapter.addChildClickViewIds(R.id.tv_cancel,R.id.tv_go);
        adapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter a, @NonNull View view, int position) {
                System.out.println(view);
                item = adapter.getItem(position);
                if (view.getId() == R.id.tv_go){
                    SelectRequestPaidan paidan = new SelectRequestPaidan(getContext(),"Bearer " +token,item.getId(),item.getPrice());
                    paidan.setOnCallback(new SelectRequestPaidan.OnCallback() {
                        @Override
                        public void onCall(Choose result, int payType) {
                            PaidanList1Fragment.this.payType = payType;
                            if (payType == 1){
                                presenter1.reqeust("Bearer " +token,result.getApplyId(),item.getId(),"1");
                            }else {
                                presenter1.reqeust("Bearer " +token,result.getApplyId(),item.getId(),"2");
                            }
                        }
                    });
                    paidan.create();

                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                    builder.setTitle("取消派单");
                    builder.setMessage("确定取消派单吗？");
                    builder.setNegativeButton("取消",null);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            presenter2.reqeust("Bearer " +token,item.getId());
                        }
                    });
                    builder.show();
                }
            }
        });
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> a, @NonNull View view, int position) {
                PaidanList2 item = adapter.getItem(position);
                if (item.getStatus() == 2 || item.getStatus() == 1){
                    Bundle bundle = new Bundle();
                    bundle.putString("id",item.getId());
                    bundle.putString("type","paidan");
                    intent(PaiDanOrderDetailActivity.class,bundle);
                }

            }
        });
        rv_bill.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_bill.setAdapter(adapter);

        refreshLayout.setOnRefreshListener(refreshLayout -> onRefreshStart());
        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> onLoadMore());


        consumerOrderListPresenter = new ConsumerOrderListPresenter(new ConsumerOrderCall());
        onRefreshStart();
    }

    @Subscribe
    public void onEventBus(String code){
        if ("refresh_paidan_list1".equals(code)){
            onRefreshStart();
        }
    }

    public void onRefreshStart(){
        consumerOrderListPresenter.reqeust("Bearer " + token,type,true);
    }

    public void onLoadMore(){
        consumerOrderListPresenter.reqeust("Bearer " + token,type,false);
    }

    public void finishRefLoad(){
        refreshLayout.finishLoadMore();
        refreshLayout.finishRefresh();
    }

    class ConsumerOrderCall implements DataCall<PaidanListResult> {

        @Override
        public void success(PaidanListResult data, Object... args) {
            finishRefLoad();
            if (consumerOrderListPresenter.isRefresh()){
                adapter.setNewInstance(data.getRecords());
            }else {
                adapter.addData(data.getRecords());
            }
            if (adapter.getData().size() > 0){
                EventBus.getDefault().post("paidan_type_1");
            }
            if (consumerOrderListPresenter.getPage() >= data.getTotal()){
                refreshLayout.setEnableLoadMore(false);
            }else {
                refreshLayout.setEnableLoadMore(true);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
            Log.e("eeeeeee", e.toString());
            finishRefLoad();
        }
    }

    String id;
    class  ChooseServiceCall implements DataCall<PayOrder> {

        @Override
        public void success(PayOrder data, Object... args) {

            id = data.getId();
//            if (payType == 0) {
//                if (data.getStatus().equals("0")) {
//                    UIUtils.showToastSafe("您的余额不足，请充值");
//                } else {
//                    payOrderSure();
//                }
//            } else
            if (payType == 0) {
                String retString = data.getRetString();
                payOrderForAlipay(retString);
            } else {
                payOrderForWx(data);
            }

        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    class  CancelCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            onRefreshStart();

        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                onRefreshStart();
                Bundle bundle = new Bundle();
                bundle.putString("id",item.getId());
                bundle.putString("type","paidan");
                intent(PaiDanOrderDetailActivity.class,bundle);
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                UIUtils.showToastSafe(payResult.getMemo());
            }
        }
    };
    private void payOrderForAlipay(String retString) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(retString, true);
                Message msg = new Message();
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void payOrderForWx(PayOrder data) {
        WXPayEntryActivity.setOnCallback(new OnCallback<Boolean>() {
            @Override
            public void onCall(Boolean result) {
                if (result){
                    onRefreshStart();
                    Bundle bundle = new Bundle();
                    bundle.putString("id",item.getId());
                    bundle.putString("type","paidan");
                    intent(PaiDanOrderDetailActivity.class,bundle);
                }else {
                    Toast.makeText(getContext(), "支付失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        IWXAPI wxapi = WXAPIFactory.createWXAPI(getContext(), WXPayEntryActivity.APP_ID, true);
        // 将应用的appId注册到微信
        wxapi.registerApp(WXPayEntryActivity.APP_ID);

        PayReq req = new PayReq();
        req.appId = data.getAppId();
        req.partnerId = data.getPartnerId();
        req.prepayId = data.getPrePayId();
        req.packageValue = data.get_package();
        req.nonceStr = data.getNonceStr();
        req.timeStamp = data.getTimestamp();
//        req.extData = extData;
        req.sign = data.getSign();

        // 调起微信支付页面
        boolean result = wxapi.sendReq(req);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
